package com.lgl.generator;

import com.lgl.model.MainTemplateModel;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import lombok.Data;

import java.io.*;

/**
 * @author 良哥
 * @verison 1.0
 */

public class DynamicGenerator {

    public static void main(String[] args) throws TemplateException, IOException {

        String propertyPath = System.getProperty("user.dir");
        String inputPath = propertyPath + "/code_generate_basic/src/main/resources/templates/MainTemplate.java.ftl";

        String outputPath = propertyPath + "/code_generate_basic/MainTemplate.java";

        MainTemplateModel model = new MainTemplateModel();
        model.setAuthor("六公1里");
        model.setIsLoop(false);


        System.out.println(inputPath);
        System.out.println(outputPath);
        TemplateConfig(inputPath, outputPath, model);
    }

    public static void TemplateConfig(String inputPath, String outputPath, Object model) throws IOException, TemplateException {

        // new 出 Configuration 对象，参数为 FreeMarker 版本号
        Configuration configuration = new Configuration(Configuration.VERSION_2_3_32);

        // 指定模板文件所在的路径
        File templateDir = new File(inputPath).getParentFile();
        configuration.setDirectoryForTemplateLoading(templateDir);

        // 设置模板文件使用的字符集
        configuration.setDefaultEncoding("utf-8");

        // 创建模板对象，加载指定模板
        String templateName = new File(inputPath).getName();
        Template template = configuration.getTemplate(templateName);


        Writer outer = new OutputStreamWriter(new FileOutputStream(outputPath), "UTF-8");
        template.process(model, outer);

        // 生成文件后别忘了关闭哦
        outer.close();
    }
}
